package com.example.helloworld.mq.service;

import com.example.helloworld.mq.constant.AmqpConstants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DelayedMessageConsumer {

    /**
     * 监听延迟队列，接收延迟消息
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = AmqpConstants.DELAYED_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(
                    value = AmqpConstants.DELAYED_EXCHANGE_NAME,
                    type = AmqpConstants.DELAYED_TYPE,
                    arguments = @Argument(name = "x-delayed-type", value = "direct")
            ),
            key = {"delayed.routing.key"})})
    public void receiveDelayedMessage(String message, Channel channel,
                                      @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        // 打印接收时间
        String receiveTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("接收消息：" + message + "，接收时间：" + receiveTime);

        channel.basicAck(tag, false);
    }
}
